from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token
from app.admin.models.admin import Admin

# 管理端接口前缀：/api/admin
admin_auth_bp = Blueprint('admin_auth', __name__, url_prefix='/api/admin')

@admin_auth_bp.post('/login')
def admin_login():
    """管理员登录接口"""
    data = request.get_json()
    if not data or "username" not in data or "password" not in data:
        return jsonify({"code": -1, "msg": "缺少用户名或密码"}), 400
    
    # 验证账号密码
    admin = Admin.verify_login(data["username"], data["password"])
    if not admin:
        return jsonify({"code": -1, "msg": "用户名或密码错误"}), 401
    
    # 生成JWT（有效期12小时）
    token = create_access_token(identity=str(admin["_id"]), additional_claims={"role": admin["role"]})
    return jsonify({
        "code": 0,
        "msg": "登录成功",
        "data": {
            "token": token,
            "username": admin["username"],
            "role": admin["role"]
        }
    })